#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Predesys Server - Core - XML tool
@version: 0.2.5
@license: GPL 3.0 (see "license" file)
@author: Jose A. Jimenez
@contact: jajimc@gmail.com"""

import sys
sys.dont_write_bytecode = True
import os
import os.path
import xml.dom.minidom
import exceptions
    
class SimpleXmlDocument():
    """Class for parse a simple XML document. It only provides access to text nodes values."""
    def __init__(self, path):
        """Class constructor.
        @param path: XML file path
        @type path: C{str}
        @raise FileNotFoundException: If path doesn't exist
        @raise ParseXmlException: If an error occurs parsing the XML file"""
        if not (os.path.exists(path) and os.path.isfile(path)):
            raise FileNotFoundException("Configuration file not found.")
            
        try:
            self.document = xml.dom.minidom.parse(path)
        except:
            raise ParseXmlException("Error parsing configuration file.")
    
    def get_text_node_value(self, tagName, index):
        """Returns the value of a text node.
        @param tagName: Node tag name
        @type tagName: C{str}
        @param index: Index of the node array associated to tag name
        @type index: C{int}
        @return: Node value
        @rtype: C{str}
        @raise ParseXmlException: If an error occurs parsing the XML file"""
        try:
            text = str(self.__get_text(self.document.getElementsByTagName(tagName)[index].childNodes))
        except:
            raise ParseXmlException("Node tag name or node index not valid.")

        return text
        
    def __get_text(self, nodeList):    
        """Given a text node, it returns its value.
        @param nodeList: Text node
        @type nodeList: C{str}
        @return: Node value
        @rtype: C{str}"""
        text = []
        for node in nodeList:
            if node.nodeType == node.TEXT_NODE:
                text.append(node.data)
        return "".join(text)
        
class FileNotFoundException(exceptions.Exception):
    pass
    
class ParseXmlException(exceptions.Exception):
    pass
